<template>
  <div>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <Button type="primary" @click="handleAllocation()">新增</Button>
      <Table
        size="small"
        :loading="tableLoading"
        :columns="columns"
        :data="data"
        class="ivu-mt-16"
      >
        <template slot-scope="{ row }" slot="status">
          <Button v-if="row.status === '1'" type="success" size="small"
            >启用</Button
          >
          <Button v-if="row.status === '0'" type="error" size="small"
            >停用</Button
          >
        </template>
        <template slot-scope="{ row }" slot="operation">
          <a @click="handleAllocation(row)">编辑</a>
          <Divider type="vertical" />
          <a class="deleteBtn" @click="handleDelete(row)">删除</a>
        </template>
      </Table>
    </Card>
    <Modal
      v-model="modal"
      :title="edit ? '编辑' : '新增'"
      :mask-closable="false"
      draggable
      @on-cancel="handleDrawerCancel()"
    >
      <Form
        :model="formItem"
        :rules="ruleValidate"
        ref="formItem"
        :label-width="118"
      >
        <FormItem label="标签组名称" prop="input">
          <Input
            v-model="formItem.input"
            placeholder="请输入"
            clearable
          ></Input>
        </FormItem>
        <FormItem
          v-for="(item, inum) in formItem.items"
          :key="inum"
          :label="'标签 ' + item.index"
          :prop="'items[' + inum + '].value'"
          :rules="{
            required: true,
            message: '标签 ' + item.index + ' 请录入内容',
            trigger: 'blur',
          }"
        >
          <Row>
            <Col span="18">
              <Input
                type="text"
                v-model="item.value"
                placeholder="输入子标签..."
                clearable
              ></Input>
            </Col>
            <Col span="4" offset="1">
              <Button
                type="error"
                @click="handleRemove(item, formItem.items, inum)"
                >删除</Button
              >
            </Col>
          </Row>
        </FormItem>
        <FormItem>
          <Row>
            <Col span="12">
              <Button type="dashed" long @click="handleAdd" icon="md-add"
                >新增标签</Button
              >
            </Col>
          </Row>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="handleDrawerCancel()">取消</Button>
        <Button
          type="primary"
          :loading="loading"
          @click="handleSubmit('formItem')"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  GetTagsList,
  CreateTags,
  UpdateTags,
  DeleteTagsStatus,
  deleteTagsChild,
} from "@api/setting";
import { mapState } from "vuex";

export default {
  name: "diagnosis",
  data() {
    return {
      index: 1,
      modal: false,
      edit: false,
      loading: false,
      tableLoading: false,
      deleteArr: [],
      formItem: {
        input: "",
        items: [
          {
            value: "",
            index: 1,
            have_bind: "",
          },
        ],
      },
      ruleValidate: {
        input: [
          { required: true, message: "便签组名不可为空", trigger: "blur" },
        ],
      },
      columns: [
        {
          title: "标签组",
          key: "group_name",
        },
        {
          title: "子标签",
          key: "tags_name",
        },
        {
          title: "操作",
          slot: "operation",
        },
      ],
      data: [],
    };
  },
  computed: {
    ...mapState(["admin"]),
    projectId() {
      return this.admin.user.info.project_id;
    },
  },
  created() {
    this.onLoad();
  },
  methods: {
    onLoad() {
      /**
       * @description 标签列表 默认不传
       * @param {Object} param page  {String} 页数
       * @param {Object} param pageSize {String} 条数/页
       */
      this.tableLoading = true;
      GetTagsList()
        .then((res) => {
          this.data = res.list;
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    handleAllocation(row) {
      this.modal = true;
      if (row) {
        this.edit = true;
        this.formItem = {
          input: row.group_name,
          items: this.filteTags(row.tags_list),
          id: row.id,
        };
        this.index = this.formItem.items.length;
      }
    },
    filteTags(String) {
      let reArr = [];
      if (String) {
        if (String && String.length > 0) {
          String.forEach((item, inum) => {
            reArr.push({
              value: item.tags_name,
              tags_id: item.id ? item.id : 0,
              index: inum + 1,
              have_bind: item.have_bind,
            });
          });
        }
      }
      return reArr;
    },

    /* *** 注释信息 @author Zhou @date 2020/2/16 *** */
    /* 删除效果类型 备用
            /* ******************************************** */
    handleDelete(row) {
      const param = {
        id: row.id,
      };
      this.$Modal.confirm({
        title: "删除标签",
        content:
          '确定删除当前标签组<span style="color:#ed4014">' +
          row.group_name +
          "</span>?",
        onOk: () => {
          this.deleteSubmit(param);
        },
      });
    },
    handleDrawerCancel() {
      this.modal = false;
      this.edit = false;
      this.index = 1;
      this.formItem.items = [
        {
          value: "",
          index: 1,
        },
      ];
      this.onLoad();
    },
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.loading = true;
          const params = {
            group_name: this.formItem.input,
            project_id: this.projectId,
            list: this.filterSubTags(this.formItem.items),
          };
          if (this.edit) {
            params.id = this.formItem.id;
            this.updateSubmit(params);
          } else {
            this.createSubmit(params);
          }
        } else {
          console.log("表单校验失败！");
        }
      });
    },
    filterSubTags(arr) {
      let reArr = [];
      if (arr && arr.length > 0) {
        arr.forEach((item) => {
          reArr.push({
            tags_name: item.value,
            tags_id: item.tags_id ? item.tags_id : 0,
          });
        });
      }
      return reArr;
    },
    handleAdd() {
      this.index++;
      this.formItem.items.push({
        value: "",
        index: this.index,
      });
    },
    handleRemove(index, e, r) {
      if (this.formItem.items[r].have_bind === undefined) {
        this.formItem.items.splice(r, 1);
        this.index = this.formItem.items.length;
      }
      if (index.have_bind === 1) {
        // if (this.index > 1) {
        //     deleteTagsChild({ tags_id: index.tags_id }).then(res => {
        //     })
        // } else {
        //     this.$Message.warning(' 至少录入一个子标签');
        // }
        deleteTagsChild({ tags_id: index.tags_id }).then((res) => {});
        this.formItem.items.splice(r, 1);
        this.index = this.formItem.items.length;
        this.$Message.info("删除成功");
      } else if (index.have_bind === 0) {
        this.$Modal.confirm({
          title: "删除标签",
          content: "<p>已有患者绑定该标签，是否确认删除？</p>",
          onOk: () => {
            deleteTagsChild({ tags_id: index.tags_id }).then((res) => {});
            this.formItem.items.splice(r, 1);
            this.index = this.formItem.items.length;
            this.$Message.info("删除成功");
          },
          onCancel: () => {
            this.$Message.info("取消成功");
          },
        });
      }
    },
    filteReTags(arr) {
      let reArr = [];
      if (arr && arr.length > 0) {
        arr.forEach((item, inum) => {
          reArr.push({
            value: item.value,
            tags_id: item.tags_id ? item.tags_id : 0,
            index: inum + 1,
          });
        });
      }
      return reArr;
    },
    createSubmit(params) {
      CreateTags(params)
        .then(() => {
          this.$Message.success(" 创建成功");
          this.loading = false;
          this.onLoad();
          this.handleDrawerCancel();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    updateSubmit(params) {
      UpdateTags(params)
        .then(() => {
          this.$Message.success(" 修改成功");
          this.loading = false;
          this.onLoad();
          this.handleDrawerCancel();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    deleteSubmit(params) {
      // 调用删除接口  备用
      DeleteTagsStatus(params).then(() => {
        this.$Message.success(" 删除成功");
        this.onLoad();
      });
    },
  },
};
</script>
